package com.srwl.mytx.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.alibaba.fastjson.JSONObject;
import com.github.florent37.viewanimator.ViewAnimator;
import com.srwl.mytx.Constant;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.domain.InviteExtraInfo;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.StringUtil;

import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
//import io.agora.AgoraAPIOnlySignal;
//import io.agora.rtc.Constants;
//import io.agora.rtc.IRtcEngineEventHandler;
//import io.agora.rtc.RtcEngine;
//import io.agora.rtc.video.VideoCanvas;
//import io.agora.rtc.video.VideoEncoderConfiguration;

/**
 * 声网 语音/视频通话页面
 */
public class VideoChatViewActivity extends AppCompatActivity {

    private static final String TAG = VideoChatViewActivity.class.getSimpleName();

    private static final int PERMISSION_REQ_ID_RECORD_AUDIO = 22;
    private static final int PERMISSION_REQ_ID_CAMERA = PERMISSION_REQ_ID_RECORD_AUDIO + 1;
    private String channelId;
    //    private RtcEngine mRtcEngine;// Tutorial Step 1
    private User targetUser;
    //    private final IRtcEngineEventHandler mRtcEventHandler = new IRtcEngineEventHandler() { // Tutorial Step 1
//        @Override
//        public void onJoinChannelSuccess(String channel, int uid, int elapsed) {
//            Log.d(TAG, "语音/视频通话进入频道成功：" + channel + ":" + uid);
//            if (isHadReceive) {
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        tv_status.setText("已连接");
//                    }
//                });
//            }
//        }
//
//        @Override
//        public void onUserJoined(int uid, int elapsed) {
//
//            Log.d(TAG, "语音/视频通话有人进入：" + uid);
//        }
//
//        @Override
//        public void onError(int err) {
//            Log.e(TAG, "语音/视频通话错误：" + err);
//        }
//
//        @Override
//        public void onFirstRemoteVideoDecoded(final int uid, int width, int height, int elapsed) { // Tutorial Step 5
//            runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    setupRemoteVideo(uid);
//                }
//            });
//        }
//
//        @Override
//        public void onUserOffline(int uid, int reason) { // Tutorial Step 7
//            runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    onRemoteUserLeft();
//                }
//            });
//        }
//
//        @Override
//        public void onUserMuteVideo(final int uid, final boolean muted) { // Tutorial Step 10
//            runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
////                    //如果远程视频没有初始化过，需要初始化远程视频View
////                    if (!hasInitRemoteVideo) {
////                        mRtcEngine.enableVideo();
////                        setupRemoteVideo(uid);
////                    }
////                    //本地视频没有初始化过，说明是语音转视频，而此时是接收到来自对方的视频，自己的视频无须传给对方，手动关闭掉
////                    if (!hasInitLocalVideo) {
////                        mRtcEngine.muteLocalVideoStream(false);
////                    }
//                    onRemoteUserVideoMuted(uid, muted);
//                }
//            });
//        }
//    };
    private String type;
    private boolean inviteFaile;
    private boolean isReceived;
    @BindView(R.id.tv_nick)
    TextView tv_nick;
    @BindView(R.id.iv_avatar)
    ImageView iv_avatar;
    @BindView(R.id.tv_status)
    TextView tv_status;
    @BindView(R.id.ll_ready)
    View ll_ready;
    @BindView(R.id.iv_receive)
    ImageView iv_receive;
    @BindView(R.id.ll_start_call)
    View ll_startCall;
    @BindView(R.id.rl_control_local_video)
    RelativeLayout rl_controlLocalVideo;
    @BindView(R.id.rl_switch_camera)
    RelativeLayout rl_switchCamera;
    //    private AgoraAPIOnlySignal agoraAPIOnlySignal;
    private BroadcastReceiver receiver;
    private LocalBroadcastManager broadcastManager;
    private FrameLayout localVideoContainer;
    private FrameLayout remoteVideoContainer;
    private RelativeLayout rl_userInfo;
    private SurfaceView surfaceViewLocal;
    private SurfaceView surfaceViewRemote;
    private boolean isShowLocalVideo;

    private DisplayMetrics displayMetrics;
    private boolean hasInitLocalVideo;
    private boolean isVideoCall;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置不黑屏等
        getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                        | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                        | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

        setContentView(R.layout.activity_video_chat_view);

        displayMetrics = getResources().getDisplayMetrics();
        ButterKnife.bind(this);
//        agoraAPIOnlySignal = MyApplication.getInstance().getmAgoraAPI();
        targetUser = getIntent().getParcelableExtra("targetUserInfo");
        type = getIntent().getStringExtra("type");
        if (type.equals(Constant.INVITE_TYPE_VIDEO_CALL)) {
            isVideoCall = true;
        }
        isReceived = getIntent().getBooleanExtra("isHadReceive", false);
        //如果是被叫方，频道号就是对方传过来的，如果是主叫方，就uuid生成一个，并在呼叫对方的时候，传递给对方，
        if (isReceived) {
            channelId = getIntent().getStringExtra("channelID");
        } else {
            channelId = UUID.randomUUID().toString();
        }
        initView();
        // int status = agoraAPIOnlySignal.getStatus();
//        if (status == 0) {//未登录状态
//            Helper.getInstance().loginToAgora();
//        }
//        registerBroadcastReceiver();
//        Log.d(TAG, "登录状态:" + status);
        if (checkSelfPermission(Manifest.permission.RECORD_AUDIO, PERMISSION_REQ_ID_RECORD_AUDIO) && checkSelfPermission(Manifest.permission.CAMERA, PERMISSION_REQ_ID_CAMERA)) {
            //如果不是接收方，就发送一条邀请 呼叫信息出去
            if (!isReceived) {
                sendInviteMessage();
            }
            initAgoraEngineAndJoinChannel();
        }
    }

    private void sendInviteMessage() {
        InviteExtraInfo info = new InviteExtraInfo();
        info.setType(type);
        info.setFrom(UserProfileManager.getInstance().getLoginUserInfo().getuId());
//        agoraAPIOnlySignal.channelInviteUser2(channelId, targetUser.getuId(), JSONObject.toJSONString(info));
    }

    private void initView() {
        localVideoContainer = findViewById(R.id.local_video_view_container);
        remoteVideoContainer = findViewById(R.id.remote_video_view_container);
        rl_userInfo = findViewById(R.id.rl_user_info);
        // localVideoContainer.setVisibility(View.INVISIBLE);
        //切换本地、远程视频的显示位置
        localVideoContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


//                int indexOfChild = remoteVideoContainer.indexOfChild(remoteVideoContainer);
//                int indexOfChild1 = rootView.indexOfChild(localVideoContainer);
//                Log.d(TAG,"大容器层级："+indexOfChild);
//                Log.d(TAG,"小容器层级："+indexOfChild1);
//
//                remoteVideoContainer.removeAllViews();
//                localVideoContainer.removeAllViews();
//                //根据小容器装的视频源，切换本地、远程视频的显示位置
//                if (isSmallContainerLocalVideo) {
//                    isSmallContainerLocalVideo=false;
//                    remoteVideoContainer.addView(surfaceViewLocal);
//                    localVideoContainer.addView(surfaceViewRemote);
//                    localVideoContainer.bringChildToFront(surfaceViewRemote);
//
//                }else {
//                    isSmallContainerLocalVideo=true;
//                    remoteVideoContainer.addView(surfaceViewRemote);
//                    localVideoContainer.addView(surfaceViewLocal);
//
//                }
//                int indexOfChild2 = rootView.indexOfChild(remoteVideoContainer);
//                int indexOfChild3 = rootView.indexOfChild(localVideoContainer);
//                Log.d(TAG,"切换之后大容器层级："+indexOfChild2);
//                Log.d(TAG,"切换之后小容器层级："+indexOfChild3);

            }
        });
        //如果是呼叫方，就隐藏接听按键
        if (!isReceived) {
            iv_receive.setVisibility(View.GONE);

            if (isVideoCall) {//如果是视频呼叫，让背景透明
                rl_userInfo.setBackground(new ColorDrawable(Color.TRANSPARENT));
            }
        } else {

            if (isVideoCall) {
                tv_status.setText("视频通话等待接听...");

            } else {

                tv_status.setText("语音通话等待接听...");
            }
        }

        if (!isVideoCall) {
            rl_controlLocalVideo.setVisibility(View.GONE);
            rl_switchCamera.setVisibility(View.GONE);
        }

        //Glide.with(this).load(targetUser.getAvatar()).diskCacheStrategy(DiskCacheStrategy.ALL).error(R.drawable.tx_default_avatar).into(iv_avatar);
        GlideLoadUtils.glideLoad(this, targetUser.getAvatar(), iv_avatar, R.drawable.tx_default_avatar_1);
        tv_nick.setText(targetUser.getUsername());
    }

    private void initAgoraEngineAndJoinChannel() {
        initializeAgoraEngine();
        //如果是视频通话，才初始化本地视频
        if (isVideoCall) {
            setupVideoProfile();
            setupLocalVideo();
        }


        //如果是发起呼叫，那就直接加入频道
        if (!isReceived) {
            joinChannel();
        }
    }

    public boolean checkSelfPermission(String permission, int requestCode) {
        Log.i(TAG, "checkSelfPermission " + permission + " " + requestCode);
        if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
            return false;
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String permissions[], @NonNull int[] grantResults) {
        Log.i(TAG, "onRequestPermissionsResult " + grantResults[0] + " " + requestCode);

        switch (requestCode) {
            case PERMISSION_REQ_ID_RECORD_AUDIO: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    checkSelfPermission(Manifest.permission.CAMERA, PERMISSION_REQ_ID_CAMERA);
                } else {
                    showLongToast("No permission for " + Manifest.permission.RECORD_AUDIO);

                    finish();
                }
                break;
            }
            case PERMISSION_REQ_ID_CAMERA: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (!isReceived) {
                        sendInviteMessage();
                    }
                    initAgoraEngineAndJoinChannel();
                } else {
                    showLongToast("No permission for " + Manifest.permission.CAMERA);

                    finish();
                }
                break;
            }
        }
    }

    public final void showLongToast(final String msg) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Helper.getInstance().setStartingCall(false);
        broadcastManager.unregisterReceiver(receiver);
        leaveChannel();
//        RtcEngine.destroy();
//        mRtcEngine = null;
    }

    public void onLocalVideoMuteClicked(View view) {
        //如果是语音状态，没有打开过视频，则需要开启视频，否则对方收到的是黑屏，，
//        if (!hasInitRemoteVideo) {
//            mRtcEngine.enableVideo();
//        }
//        if (!hasInitLocalVideo) {
//            setupLocalVideo();
//        }
        ImageView iv = (ImageView) view;
        if (iv.isSelected()) {
            iv.setSelected(false);
            iv.clearColorFilter();
        } else {
            iv.setSelected(true);
            iv.setColorFilter(getResources().getColor(R.color.gray_background_2), PorterDuff.Mode.MULTIPLY);
        }

//        mRtcEngine.muteLocalVideoStream(iv.isSelected());
        if (localVideoContainer.getVisibility() == View.VISIBLE) {
            localVideoContainer.setVisibility(View.GONE);
        }
//
//        FrameLayout container = (FrameLayout) findViewById(R.id.local_video_view_container);
//        SurfaceView surfaceView = (SurfaceView) container.getChildAt(0);
//        surfaceView.setZOrderMediaOverlay(!iv.isSelected());
//        surfaceView.setVisibility(iv.isSelected() ? View.GONE : View.VISIBLE);
        surfaceViewLocal.setVisibility(iv.isSelected() ? View.GONE : View.VISIBLE);
    }

    public void onLocalAudioMuteClicked(View view) {
        ImageView iv = (ImageView) view;
        if (iv.isSelected()) {
            iv.setSelected(false);
            // iv.clearColorFilter();
        } else {
            iv.setSelected(true);
            //  iv.setColorFilter(getResources().getColor(R.color.gray_background_2), PorterDuff.Mode.MULTIPLY);
        }

//        mRtcEngine.muteLocalAudioStream(iv.isSelected());
    }

    public void onSwitchCameraClicked(View view) {
        ImageView iv = (ImageView) view;

        if (iv.isSelected()) {
            ViewAnimator.animate(iv).rotationY(0, 195, 165, 180).start();
            iv.setSelected(false);
            //iv.clearColorFilter();
        } else {
            ViewAnimator.animate(iv).rotationY(180, -15, 15, 0).start();
            iv.setSelected(true);
            //iv.setColorFilter(getResources().getColor(R.color.gray_background_2), PorterDuff.Mode.MULTIPLY);
        }

//        mRtcEngine.switchCamera();
    }

    public void onEncCallClicked(View view) {
        finish();
    }

    private void initializeAgoraEngine() {
        try {
//            mRtcEngine = RtcEngine.create(getBaseContext(), getString(R.string.agora_id), mRtcEventHandler);
//            mRtcEngine.setChannelProfile(Constants.CHANNEL_PROFILE_COMMUNICATION);
        } catch (Exception e) {
            Log.e(TAG, "初始化声网RTC引擎失败：" + Log.getStackTraceString(e));

            throw new RuntimeException("NEED TO check rtc sdk setupView fatal error\n" + Log.getStackTraceString(e));
        }
    }

    private void setupVideoProfile() {
//        mRtcEngine.enableVideo();

//      mRtcEngine.setVideoProfile(Constants.VIDEO_PROFILE_360P, false); // Earlier than 2.3.0
//        mRtcEngine.setVideoEncoderConfiguration(new VideoEncoderConfiguration(VideoEncoderConfiguration.VD_640x360, VideoEncoderConfiguration.FRAME_RATE.FRAME_RATE_FPS_15,
//                VideoEncoderConfiguration.STANDARD_BITRATE,
//                VideoEncoderConfiguration.ORIENTATION_MODE.ORIENTATION_MODE_FIXED_PORTRAIT));
    }


    private void setupLocalVideo() {
        hasInitLocalVideo = true;
//        surfaceViewLocal = RtcEngine.CreateRendererView(getBaseContext());

//        surfaceViewLocal.setZOrderMediaOverlay(true);
//        surfaceViewLocal.setZOrderOnTop(true);
        //设置点击监听，切换本地 远程视频的大小

//        localVideoContainer.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onExtendMenuItemClick(View v) {
//                if (isSmallContainerLocalVideo) {
//                    isSmallContainerLocalVideo = false;
//                    remoteVideoContainer.removeAllViews();
//                    localVideoContainer.removeAllViews();
//                    remoteVideoContainer.addView(surfaceViewLocal);
//                    surfaceViewRemote.setZOrderOnTop(true);
//                    surfaceViewRemote.setZOrderMediaOverlay(true);
//                    localVideoContainer.addView(surfaceViewRemote);
//                } else {
//                    isSmallContainerLocalVideo = true;
//                    remoteVideoContainer.removeAllViews();
//                    localVideoContainer.removeAllViews();
//                    remoteVideoContainer.addView(surfaceViewRemote);
//                    surfaceViewLocal.setZOrderOnTop(true);
//                    surfaceViewLocal.setZOrderMediaOverlay(true);
//                    localVideoContainer.addView(surfaceViewLocal);
//                }
//            }
//        });
        // remoteVideoContainer.addView(surfaceViewLocal);
        //设置点击监听，大视频展示本地视频，小视频展示远程视频
        surfaceViewLocal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isShowLocalVideo && surfaceViewRemote != null) {
                    isShowLocalVideo = true;
                    FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
                    FrameLayout.LayoutParams layoutParamsSmall = new FrameLayout.LayoutParams((int) (80 * displayMetrics.density), (int) (142 * displayMetrics.density));
                    // layoutParamsSmall.gravity = Gravity.END;
                    surfaceViewLocal.setLayoutParams(layoutParams);
                    remoteVideoContainer.removeView(surfaceViewRemote);
                    surfaceViewRemote.setLayoutParams(layoutParamsSmall);
                    surfaceViewRemote.setZOrderOnTop(true);
                    surfaceViewRemote.setZOrderMediaOverlay(true);
                    remoteVideoContainer.addView(surfaceViewRemote);

                }
            }
        });

        remoteVideoContainer.addView(surfaceViewLocal);

//        mRtcEngine.setupLocalVideo(new VideoCanvas(surfaceViewLocal, VideoCanvas.RENDER_MODE_ADAPTIVE, 0));
    }

    private void joinChannel() {
//        mRtcEngine.joinChannel(null, channelId, "Extra Optional Data", 0); // if you do not specify the uid, we will generate the uid for you
    }

    private void setupRemoteVideo(int uid) {
        //隐藏cover
        if (rl_userInfo.getVisibility() == View.VISIBLE) {
            rl_userInfo.setVisibility(View.GONE);
        }

        //获得远程视频，并加入容器container
//        surfaceViewRemote = RtcEngine.CreateRendererView(getBaseContext());
//        mRtcEngine.setupRemoteVideo(new VideoCanvas(surfaceViewRemote, VideoCanvas.RENDER_MODE_ADAPTIVE, uid));
        remoteVideoContainer.removeAllViews();
        remoteVideoContainer.addView(surfaceViewRemote, 0);
        surfaceViewRemote.setTag(uid); // for mark purpose

        //如果已经初始化了本地视频，则需要切换本地、远程视频的大小
        if (hasInitLocalVideo) {

            //当视频通话接通的时候，让本地视频变小
            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams((int) (80 * displayMetrics.density), (int) (142 * displayMetrics.density));
            //layoutParams.gravity = Gravity.END;
            // remoteVideoContainer.removeView(surfaceViewLocal);
            surfaceViewLocal.setLayoutParams(layoutParams);
            surfaceViewLocal.setZOrderOnTop(true);
            surfaceViewLocal.setZOrderMediaOverlay(true);
            remoteVideoContainer.addView(surfaceViewLocal);
        }


        //设置点击监听，大视频展示远程视频，小视频展示本地
        surfaceViewRemote.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isShowLocalVideo && surfaceViewLocal != null) {
                    isShowLocalVideo = false;
                    FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
                    FrameLayout.LayoutParams layoutParamsSmall = new FrameLayout.LayoutParams((int) (80 * displayMetrics.density), (int) (142 * displayMetrics.density));
                    //layoutParamsSmall.gravity = Gravity.END;
                    surfaceViewRemote.setLayoutParams(layoutParams);
                    remoteVideoContainer.removeView(surfaceViewLocal);
                    surfaceViewLocal.setLayoutParams(layoutParamsSmall);
                    surfaceViewLocal.setZOrderOnTop(true);
                    surfaceViewLocal.setZOrderMediaOverlay(true);
                    remoteVideoContainer.addView(surfaceViewLocal);
                }
            }
        });
        // rootView.addView(surfaceViewRemote, 0);


    }

    // Tutorial Step 6
    private void leaveChannel() {
//        mRtcEngine.leaveChannel();
    }

    // Tutorial Step 7
    private void onRemoteUserLeft() {
        remoteVideoContainer.removeAllViews();
        tv_status.setText("连接已经断开");
        if (!rl_userInfo.isShown()) {
            rl_userInfo.setVisibility(View.VISIBLE);
        }
        postDelayedFinish(2000);

    }

    // Tutorial Step 10
    private void onRemoteUserVideoMuted(int uid, boolean muted) {
//        FrameLayout container = (FrameLayout) findViewById(R.id.remote_video_view_container);
//
//        SurfaceView surfaceView = (SurfaceView) container.getChildAt(0);
//
//        Object tag = surfaceView.getTag();
//        if (tag != null && (Integer) tag == uid) {
//            surfaceView.setVisibility(muted ? View.GONE : View.VISIBLE);
//        }

        surfaceViewRemote.setVisibility(muted ? View.GONE : View.VISIBLE);

        rl_userInfo.setVisibility(muted ? View.VISIBLE : View.GONE);
    }

    @OnClick(R.id.iv_receive)
    public void onReceiveCall() {
        //接受邀请
//        agoraAPIOnlySignal.channelInviteAccept(channelId, targetUser.getuId(), 0, "");
        //接听后需要隐藏掉桌面的一些控件
        tv_status.setText("连接中...");
//        if (isVideoCall) {
//            iv_avatar.setVisibility(View.GONE);
//            tv_nick.setVisibility(View.GONE);
//
//        }
        ll_ready.setVisibility(View.GONE);
        ll_startCall.setVisibility(View.VISIBLE);
        joinChannel();
    }

    @OnClick(R.id.iv_refuse_call)
    public void onRefuseCall() {
        //如果是被呼叫方，那么这个按键就是拒绝接听，如果是呼叫方，那就是主动取消呼叫
        if (isReceived) {
//            agoraAPIOnlySignal.channelInviteRefuse(channelId, targetUser.getuId(), 0, "");
            tv_status.setText("拒绝接听");
            postDelayedFinish();
        } else {
            //如果是呼叫失败，直接延迟1s后退出
            if (!inviteFaile) {
//                agoraAPIOnlySignal.channelInviteEnd(channelId, targetUser.getuId(), 0);
                tv_status.setText("取消呼叫");

            }
            postDelayedFinish();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    private void registerBroadcastReceiver() {

        broadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.ACTION_ON_INVITE_RECEIVED_BY_PEER);
        filter.addAction(Constant.ACTION_ON_INVITE_ACCEPTED_BY_PEER);
        filter.addAction(Constant.ACTION_ON_HANG_UP);
        filter.addAction(Constant.ACTION_ON_CALL_ERROR);
        filter.addAction(Constant.ACTION_ON_INVITE_END_BY_PEER);

        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                switch (intent.getAction()) {
                    case Constant.ACTION_ON_INVITE_RECEIVED_BY_PEER:
                        Log.d(TAG, "对方已经收到邀请");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tv_status.setText("等待对方接听");
                            }
                        });
                        break;
                    case Constant.ACTION_ON_INVITE_ACCEPTED_BY_PEER:
                        Log.d(TAG, "对方已经接受邀请");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
//                                if (isVideoCall) {
//                                    iv_avatar.setVisibility(View.GONE);
//                                    tv_nick.setVisibility(View.GONE);
//
//                                }
                                ll_ready.setVisibility(View.GONE);
                                ll_startCall.setVisibility(View.VISIBLE);
                                tv_status.setText("已接通");
                            }
                        });
                        break;

                    case Constant.ACTION_ON_HANG_UP:
                        Log.d(TAG, "对方已经拒绝邀请");
                        final String extra = intent.getStringExtra("extra");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //先看拒绝是否有携带附加信息，如果有，可能是“对方正在接听中”，如果没有，就是普通的“对方拒绝接听”
                                if (!StringUtil.isEmpty(extra)) {
                                    InviteExtraInfo extraInfo = JSONObject.parseObject(extra, InviteExtraInfo.class);
                                    if (extraInfo.getType().equals("busy")) {
                                        tv_status.setText("对方正在通话中");
                                    }
                                } else {
                                    tv_status.setText("对方已经拒绝接听");
                                }
                                postDelayedFinish();
                            }
                        });

                        break;
                    case Constant.ACTION_ON_CALL_ERROR:
                        int ecode = intent.getIntExtra("ecode", 0);
                        Log.d(TAG, "发起呼叫出错" + ecode);
                        inviteFaile = true;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tv_status.setText("呼叫失败，请稍后再试");
                            }
                        });
                        break;
                    case Constant.ACTION_ON_INVITE_END_BY_PEER:
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tv_status.setText("对方已经取消呼叫");
                                postDelayedFinish();
                            }
                        });


                        break;

                }
            }
        };
        broadcastManager.registerReceiver(receiver, filter);

    }

    private void postDelayedFinish() {

        postDelayedFinish(1000);
    }

    private void postDelayedFinish(int delayMillis) {
        Helper.getInstance().setStartingCall(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                finish();
            }
        }, 1000);
    }

}
